<template>
  <div class="container">
    <div>
      <div class="btn_container">
        <!-- <el-button
          class="deleteBtn"
          :disabled="!Boolean(multipleSelection.length)"
          type="danger"
          >删除选中</el-button
        > -->
        <el-dropdown @command="handleShowImage">
          <el-button class="imageDrown" type="warning">
            图文
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="singleImg">单个添加</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown @command="handleShowImage">
          <el-button class="videoDrown" type="success">
            视频
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="singleVideo"
                >单个添加</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <div class="refreshBtn" @click="getList">
          <el-icon><Refresh /></el-icon>
        </div>
      </div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="状态">
          <el-select v-model="formInline.state" multiple style="width: 100px">
            <el-option
              v-for="(value, key) in stateEnum"
              :label="value"
              :value="Number(key)"
              :key="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="delivery_time" label="任务执行时间" />
      <el-table-column prop="status" label="状态" />
      <el-table-column prop="operate" label="操作" width="200" align="center">
        <template #default="scope">
          <el-dropdown @command="(e) => handleOperate(e, scope.row)">
            <el-button class="videoDrown">
              操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">查看详情</el-dropdown-item>
                <el-dropdown-item command="delete">删除笔记</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="page_container">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="page_size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="visible"
      title="添加图文任务"
      width="800"
      center
      @close="resetForm"
    >
      <el-form
        :inline="true"
        :model="modelForm"
        ref="modelFormRef"
        label-width="100px"
      >
        <el-form-item label="标题" class="model-item" prop="title">
          <el-input v-model="modelForm.title" />
        </el-form-item>
        <el-form-item
          label="视频素材"
          class="model-item"
          prop="declarationElement"
          v-if="dropdown === 'singleVideo'"
        >
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleVideoChange"
            multiple
            v-model:file-list="videos"
            accept=".mp4,.mov,.avi,.mkv,.webm,.flv,.wmv"
          >
            <el-button type="primary">添加素材</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="上传素材" class="model-item" v-else>
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            multiple
            :on-change="handleChange"
            v-model:file-list="images"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文案" class="model-item" prop="text">
          <el-input v-model="modelForm.text" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="主动评论" class="model-item" prop="comment">
          <el-input v-model="modelForm.comment" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="投放时间" class="model-item" prop="delivery_time">
          <el-date-picker
            v-model="modelForm.delivery_time"
            type="datetime"
            placeholder="请选择投放时间"
          />
        </el-form-item>
        <el-form-item label="指定用户">
          <el-button @click="handleUser">选择</el-button>
          <el-tag
            v-for="item in user_multipleSelection"
            :key="item.id"
            closable
            @close="handleClose(item)"
            style="margin-left: 10px"
          >
            {{ item.name }}
          </el-tag>
        </el-form-item>
      </el-form>
      <div class="modalBtns">
        <el-button @click="dropdown = ''">取消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="loading"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog v-model="userShow" width="800" center>
      <div>
        <el-input
          v-model="userName"
          placeholder="请输入用户名称"
          style="width: 240px"
          clearable
        />
        <el-button
          type="primary"
          @click="handleUserSearch"
          style="margin-left: 21px"
          >搜索</el-button
        >
        <el-table
          :data="userList"
          style="width: 100%; margin-top: 10px"
          @selection-change="handleUserSelectionChange"
          ref="multipleTableRef"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="用户名" />
          <el-table-column prop="number" label="红薯号" />
          <el-table-column
            prop="creator_status"
            label="创作者cookie状态"
            width="155"
          />
        </el-table>
        <div style="margin: 20px 0">
          <el-pagination
            v-model:current-page="user_page"
            v-model:page-size="user_page_size"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="user_total"
            @size-change="handleUserSizeChange"
            @current-change="handleUserCurrentChange"
          />
        </div>
      </div>
      <div class="modalBtns">
        <!-- <el-button @click="userShow = false">取消</el-button> -->
        <el-button type="primary" @click="userShow = false">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-model="editShow"
      title="详情"
      width="500"
      center
      @close="resetForm"
    >
      <el-form
        :inline="true"
        :model="modelForm"
        ref="modelFormRef"
        label-width="100px"
      >
        <el-form-item label="标题" class="model-item" prop="declarationElement">
          <el-input v-model="modelForm.title" />
        </el-form-item>
        <el-form-item label="文案" class="model-item" prop="declarationElement">
          <el-input v-model="modelForm.text" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="deleteShow" title="提示" width="400">
      确定删除此内容
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteShow = false">取消</el-button>
          <el-button type="primary" @click="handDelete"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, watch, computed, onMounted } from "vue";
import { task_list, task_create, task_delete, xhs_list } from "@/api/xhs.js";
import { ElMessage } from "element-plus";
import { ArrowDown, Refresh, Plus } from "@element-plus/icons-vue";
import { uploadFile } from "@/utils/oss.js";
import moment from "moment";
const images = ref([]);
const videos = ref([]);
const loading = ref(false);

const handleChange = (file, uploadFiles) => {
  console.log("uploadFiles", uploadFiles);
  images.value = uploadFiles;
};
const handleVideoChange = (file, uploadFiles) => {
  videos.value = uploadFiles;
};
const page_size = ref(10);
const page = ref(1);
const user_page_size = ref(10);
const user_page = ref(1);
const user_total = ref(0);
const user_multipleSelection = ref([]);
const total = ref(0);
const tableData = ref([]);
const formInline = reactive({});
const multipleSelection = ref([]);
const modelForm = reactive({
  comment: "",
  text: "",
  title: "",
  delivery_time: new Date(),
  designated_accounts: "",
});
const modelFormRef = ref(null);
const dropdown = ref("");
const visibles = ["singleImg", "singleVideo", "batchImg"];

const visible = computed(() => visibles.includes(dropdown.value));
const editShow = ref(false);
const deleteShow = ref(false);
const selectedItem = ref({});
const userList = ref([]);
const userName = ref();
const userShow = ref(false);
const multipleTableRef = ref(null);
const toggleSelection = () => {
  if (user_multipleSelection.value.length) {
    const selected = multipleTableRef.value.getSelectionRows();
    const ids = user_multipleSelection.value.map((item) => item.id);
    const otherData = selected.filter((item) => !ids.includes(item.id));
    otherData.forEach((row) => {
      multipleTableRef.value?.toggleRowSelection(row, false);
    });
    user_multipleSelection.value.forEach((row) => {
      multipleTableRef.value?.toggleRowSelection(row, true);
    });
  } else {
    multipleTableRef.value?.clearSelection();
  }
};
const handleUser = () => {
  userShow.value = true;
  toggleSelection();
};

const handleClose = (tag) => {
  const data = user_multipleSelection.value.filter(
    (item) => item.id !== tag.id
  );
  user_multipleSelection.value = data;
};

const handleUserSelectionChange = (val) => {
  user_multipleSelection.value = val;
};

// 重置模态框的form表单
const resetForm = () => {
  dropdown.value = "";
  if (modelFormRef.value) {
    modelFormRef.value.resetFields();
  }
  Object.assign(modelForm, {
    comment: "",
    text: "",
    title: "",
    delivery_time: new Date(),
  });
  images.value = [];
  videos.value = [];
  user_multipleSelection.value = [];
};
const stateEnum = ["未开始", "进行中"];
const handleSearch = () => {
  const { state } = formInline;
  const params = {
    state,
  };
  getList(params);
};
const handleShowImage = (item) => {
  dropdown.value = item;
};
const handleOperate = (item, row) => {
  selectedItem.value = row;
  switch (item) {
    case "edit":
      editShow.value = true;
      modelForm.title = row.config.title;
      modelForm.text = row.config.text;
      break;
    case "delete":
      deleteShow.value = true;
      break;
  }
};
const handDelete = async () => {
  try {
    const res = await task_delete({
      id: selectedItem.value.id,
    });
    if (res.code === 0) {
      ElMessage.success("删除任务成功");
      await getList({ page_size: 10, page: 1 });
    } else {
      ElMessage.error(res.msg);
    }
    deleteShow.value = false;
  } catch (err) {
    console.log(err);
  }
};
const handleSizeChange = (val) => {
  page_size.value = val;
};
const handleCurrentChange = (val) => {
  page.value = val;
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const handleUserSizeChange = (val) => {
  user_page_size.value = val;
};

const handleUserCurrentChange = (val) => {
  user_page.value = val;
};

const getList = async (params) => {
  try {
    const res = await task_list({
      page_size: page_size.value,
      page: page.value,
      ...params,
    });
    if (res?.code === 0) {
      tableData.value = res.data.list;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (err) {
    console.log(err);
  }
};
const getUserList = async (params = {}) => {
  try {
    const res = await xhs_list({
      cookie_type: 0,
      page_size: user_page_size.value,
      page: user_page.value,
      name: userName.value,
      ...params,
    });
    if (res.code === 0) {
      userList.value = res.data.list;
      user_total.value = res.data.total;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (err) {
    console.log("err");
  }
};
const handleUserSearch = async () => {
  await getUserList({ page: 1 });
};
watch(
  [page_size, page],
  () => {
    getList();
  },
  {
    immediate: true,
  }
);
watch(
  [user_page_size, user_page],
  () => {
    getUserList();
  },
  {
    immediate: true,
  }
);
const downloadFile = async (resources) => {
  const paths = [];
  try {
    for (let i = 0; i < resources.length; i++) {
      const path = await window.electronAPI.downloadFile(resources[i]);
      paths.push(path);
    }
  } catch (error) {
    console.error("下载文件失败", error);
  }
  return paths;
};
const isWindows = () => {
  return navigator.userAgent.indexOf("Win") !== -1;
};
const onSubmit = async () => {
  modelFormRef.value.validate(async (valid) => {
    if (valid) {
      // 校验通过，执行提交逻辑
      try {
        loading.value = true;
        const imageResult = [];
        const videoResult = [];
        console.log("isWindow", isWindows());
        if (images.value && images.value.length) {
          const iamgePromises = images.value.map((file) => {
            return uploadFile(file.raw, file.name);
          });
          const list = await Promise.all(iamgePromises);
          let result = [];
          if (isWindows()) {
            const resources = list.map((item) => "https://" + item.Location);
            result = await downloadFile(resources);
            console.log("resources_result1", result);
          } else {
            result = images.value.map((item) => item.raw.path);
          }
          imageResult.push(...result);
        }
        if (videos.value && videos.value.length) {
          const videoPromises = videos.value.map((file) => {
            return uploadFile(file.raw, file.name);
          });
          const list = await Promise.all(videoPromises);
          let result = [];
          if (isWindows()) {
            const resources = list.map((item) => "https://" + item.Location);
            result = await downloadFile(resources);
            console.log("resources_result", result);
          } else {
            result = videos.value.map((item) => item.raw.path);
          }
          videoResult.push(...result);
        }
        const { comment, text, title, delivery_time } = modelForm;
        const res = await task_create({
          config: {
            comment: comment,
            images: imageResult,
            text: text,
            title: title,
            videos: videoResult,
            designated_accounts: user_multipleSelection.value.map((item) => {
              return {
                number: item.number,
                ads_power_id: item.ads_power_id,
                xhs_user_id: item.id,
                name: item.name,
              };
            }),
          },
          delivery_time: moment(delivery_time).format("YYYY-MM-DD HH:mm:ss"),
          type: videos.value.length ? 1 : 0,
        });
        if (res.code === 0) {
          dropdown.value = "";
          getList({ page_size: 10, page: 1 });
        } else {
          ElMessage.error(res.msg);
        }
      } catch (error) {
        console.log("error", error);
      } finally {
        images.value = [];
        videos.value = [];
        loading.value = false;
      }
    } else {
      console.log("表单校验失败");
    }
  });
};
</script>
<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  padding: 50px;
  box-sizing: border-box;
}

.page_container {
  float: right;
  margin-top: 40px;
}

:deep(.el-table__header) {
  background-color: #f5f7fa !important;
}

:deep(.el-table tr) {
  background-color: rgba(0, 0, 0, 0);
}

:deep(.el-table th.el-table__cell) {
  background-color: rgba(0, 0, 0, 0);
}
.btn_container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  .imageDrown {
    margin-left: 10px;
    color: #fff;
  }
  .deleteBtn {
    color: #fff;
  }
  .videoDrown {
    margin-left: 10px;
  }
  .refreshBtn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #78d0ec63;
    color: #78d0ecf2;
    border-radius: 50%;
    margin-left: 10px;
    cursor: pointer;
  }
}

.model-item {
  width: 90%;
}
.modalBtns {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>
